package servlet;

import com.octo.captcha.service.CaptchaServiceException;
import entity.Person;
import entity.PersonService;
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
import util.CaptchaServiceSingleton;
import util.LoginManager;
import util.Utilities;

/**
 *
 * @author HOME
 * @version
 */
public class VerificationServlet extends HttpServlet {

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        String captchaCode = request.getParameter("verification");
        boolean isCorrectCaptch = false;
        Integer logincount = (Integer) session.getAttribute("logincount");
        if (logincount == null) {
            logincount = 0;
        }

        String go = (String) request.getParameter("go");
        if (Utilities.isValid(go)) {
            go = response.encodeRedirectURL(go);
        } else {
            go = "";
        }
        String forward = "Verification.jsp?go=" + go;

        try {
            isCorrectCaptch = CaptchaServiceSingleton.getInstance().validateResponseForID(session.getId(), captchaCode);
        } catch (CaptchaServiceException e) {
            //should not happen, may be thrown if the id is not valid
        }
        if (!isCorrectCaptch) {
            forward = "Verification.jsp?go=" + go;
            logincount += 1;
            session.setAttribute("logincount", logincount);
        } else {
            //begin: copy from LoginServlet
            String loginname = request.getParameter("name");
            String pwd = request.getParameter("password");
            String remember = request.getParameter("remember");

            if (Utilities.isValid(loginname) && Utilities.isValid(pwd)) {
                //TODO: check for unactivation account, resend activation letter if necessary.
                Person person = PersonService.login(loginname, pwd);
                if (person == null) {
                    logincount += 1;
                    session.setAttribute("logincount", logincount);
                    if (logincount > 3) {
                        forward = "Verification.jsp?go=" + go;
                    } else {
                        forward = "login.jsp?msg=error&go=" + go;
                    }
                } else {
                    Cookie loginCookie = new Cookie("loginname", loginname);
                    //todo: add MD5 login hash cookies later
                    loginCookie.setMaxAge(-1);
                    //loginCookie.setSecure(true); //todo:SSL
                    //TODO: implement the remember me function
                    if (remember != null) {
                        loginCookie.setMaxAge(2592000); // 30 days
                    }
                    response.addCookie(loginCookie);
                    LoginManager.login(session, loginname, person.getPersonID());
                    if (Utilities.isValid(go)) {
                        forward = go;
                    } else {
                        forward = this.getServletContext().getContextPath();//main page
                    }
                }
            }
        //end: copy from LoginServlet
        }
        response.sendRedirect(forward);
        return;
    }

    public void loginCount(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String forward = "Verification.jsp";
        Integer logincount = (Integer) request.getSession().getAttribute("logincount");
        if (logincount == null) {
            logincount = 0;
        }
        int count = logincount.intValue();
        if (count > 0 && count <= 3) {
            request.getSession().setAttribute("logincount", count + 1);
        } else if (count > 3 && count <= 5) {
            request.getSession().setAttribute("logincount", count + 1);
            response.sendRedirect("Verification.jsp");
            return;
        } else if (count > 5) {
            response.sendRedirect("BanIP.jsp");
            return;
        } else {
            request.getSession().setAttribute("logincount", 1);
            response.sendRedirect("Verification.jsp");
            return;
        }
        return;
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
